package tech.wetech.admin.modules.system.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin.core.annotation.SystemLog;
import tech.wetech.admin.core.utils.Result;
import tech.wetech.admin.core.utils.ResultCodeEnum;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/files")
public class FilesController {
    @GetMapping
    public String files(Model model) {
        List<Map<String,String>> paths = new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        map.put("url","/usr/local/app/apache-tomcat-9.0.24/webapps/apiclient_cert/");
        map.put("name","证书默认上传目录");
        paths.add(map);

        Map<String,String> yinsheng = new HashMap<>();
        yinsheng.put("url","/usr/local/app/apache-tomcat-9.0.24/webapps/apiclient_cert/yinsheng/");
        yinsheng.put("name","银盛证书上传目录，命名规则(服务商号.pfx)");
        paths.add(yinsheng);
        model.addAttribute("paths",paths);

        Map<String,String> nonghang = new HashMap<>();
        nonghang.put("url","/usr/local/app/apache-tomcat-9.0.24/webapps/apiclient_cert/nonghang/");
        nonghang.put("name","农行证书上传目录，命名规则(商户代码.pfx)");
        paths.add(nonghang);
        model.addAttribute("paths",paths);
        return "system/files";
    }

    @SystemLog("上传文件")
    @ResponseBody
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file,@RequestParam("path") String path){
        if (!file.isEmpty()) {
            try {
                // 处理文件上传逻辑
                String fileName = file.getOriginalFilename();

                File dest = new File(path +"/"+ fileName);
                // 检查目录是否存在，不存在则创建
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                // 保存文件
                file.transferTo(dest);
                return Result.success();
            } catch (Exception e) {
                log.error("文件上传失败",e);
                return Result.failure(ResultCodeEnum.UPLOAD_FAIL);
            }
        } else {
            log.error("文件上传失败");
            return Result.failure(ResultCodeEnum.UPLOAD_FAIL);
        }

    }
}
